package com.eshop.web.component;

import com.eshop.domain.Category;
import org.apache.wicket.markup.html.tree.LinkTree;
import org.apache.wicket.model.CompoundPropertyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import java.util.List;

/**
 * Created by Sergey on 26.12.13.
 */
public class CategoriesTree extends LinkTree {
    private static final Logger LOGGER = LoggerFactory.getLogger(CategoriesTree.class);

    public CategoriesTree(String id, List<Category> categories) {
        super(id);
        setModel(new CompoundPropertyModel<TreeModel>(convertToTreeModel(categories)));
        setRootLess(true);
        getTreeState().expandAll();
    }

    private TreeModel convertToTreeModel(List<Category> list) {
        TreeModel model = null;
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new Category());
        add(rootNode, list);
        model = new DefaultTreeModel(rootNode);
        return model;
    }

    private void add(DefaultMutableTreeNode parent, List<Category> sub) {
        for (Category obj : sub) {
            if (obj != null) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(obj);
                parent.add(child);

                if (obj.getSubCategories() != null && obj.getSubCategories().size() > 0) {
                    add(child, obj.getSubCategories());
                }
            }
        }
    }
}